package bean.managed;

import entity.SalesQuotationEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.SalesQuotationEntityFacade;

import entity.CustomerEntity;
import entity.PriceListEntity;
import entity.ProductQuantityPriceEntity;
import entity.RoleEntity;
import entity.SalesInquiryEntity;
import entity.SalesLeadEntity;
import entity.SystemUserEntity;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.event.SelectEvent;
import type.CustomerType;
import util.Fixtures.Department;
import util.Mailer;

@ManagedBean(name = "salesQuotationEntityController")
@SessionScoped
public class SalesQuotationEntityController extends AbstractBacking implements Serializable {

    private SalesQuotationEntity current;
    private SalesQuotationEntity viewCurrent;
    private DataModel items = null;
    private DataModel searchItems = null;
    private DataModel unquoted = null;
    @EJB
    private bean.session.SalesQuotationEntityFacade ejbFacade;
    @EJB
    private bean.session.BackorderEntityFacade backOrderFacade;
    private PaginationHelper pagination;
    private String attribute = "id";
    private String input;
    private ProductQuantityPriceEntity currentPQP;
    private ProductQuantityPriceEntity currentPQP2;
    private ProductQuantityPriceEntity currentPQP3;
    private ProductQuantityPriceEntity currentPQP4;
    private SalesLeadEntity selectedSalesLead;
    private CustomerEntity selectedCustomer;
    @ManagedProperty(value = "#{salesInquiryEntityController}")
    private SalesInquiryEntityController salesInquiryEntityController;
    private SalesInquiryEntity convertingInquiry;
    private SalesLeadEntityController salesLeadEntityController;
    private CustomerEntityController customerEntityController;
    @ManagedProperty(value = "#{purchaseOrderEntityController}")
    private PurchaseOrderEntityController purchaseOrderEntityController;
    @ManagedProperty(value = "#{systemMessageController}")
    private SystemMessageController systemMessageController;
    @ManagedProperty(value = "#{completedGoodsEntityController}")
    private CompletedGoodsEntityController completedGoodsEntityController;
    private String justification;
    private String note;
    private boolean editQuantity = false;

    public SalesQuotationEntityController() {
    }

    public SalesQuotationEntity getCurrent() {
        return current;
    }

    public void setCurrent(SalesQuotationEntity current) {
        this.current = current;
    }

    public SalesLeadEntityController getSalesLeadEntityController() {
        return salesLeadEntityController;
    }

    public void setSalesLeadEntityController(SalesLeadEntityController salesLeadEntityController) {
        this.salesLeadEntityController = salesLeadEntityController;
    }

    public boolean checkSystemUser() {
        if (getCurrentUser() instanceof SystemUserEntity) {
            return true;
        }
        return false;
    }

    public boolean checkSalesLead() {
        if (getLoginSalesLead() instanceof SalesLeadEntity) {
            return true;
        }
        return false;
    }

    public boolean checkCustomer() {
        if (getLoginCustomer() instanceof CustomerEntity) {
            return true;
        }
        return false;
    }

    public ProductQuantityPriceEntity getSelectedPQP() {
        if (currentPQP == null) {
            setCurrentPQP(new ProductQuantityPriceEntity());
        }
        return currentPQP;
    }

    public ProductQuantityPriceEntity getSelectedPQP2() {
        if (currentPQP2 == null) {
            setCurrentPQP2(new ProductQuantityPriceEntity());
        }
        return currentPQP2;
    }

    public ProductQuantityPriceEntity getSelectedPQP3() {
        if (currentPQP3 == null) {
            setCurrentPQP3(new ProductQuantityPriceEntity());
        }
        return currentPQP3;
    }

    public ProductQuantityPriceEntity getSelectedPQP4() {
        if (currentPQP4 == null) {
            setCurrentPQP4(new ProductQuantityPriceEntity());
        }
        return currentPQP4;
    }

    public SalesQuotationEntity getSelected() {
        if (current == null) {
            current = new SalesQuotationEntity();
        }
        return current;
    }

    public SalesQuotationEntityFacade getFacade() {
        return ejbFacade;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/salesQuotationEntity/List?faces-redirect=true";
    }

    public String prepareView() {
        current = (SalesQuotationEntity) getItems().getRowData();
        return "View";
    }

    public String prepareCreate() {
        current = new SalesQuotationEntity();
        return "/entities/salesQuotationEntity/Create?faces-redirect=true";
    }

    public String viewAfterCreate() {
        setViewCurrent(current);
        prepareCreate();
        return "/entities/salesQuotationEntity/ViewCreate?faces-redirect=true";
    }

    public String create() {
        try {

            //Set PQP
            ProductQuantityPriceEntity pqp;

            currentPQP.setProduct(getFacade().getSalesQuotationProduct("Classic Nutri Bar (Nuts)"));
            current.getPqp().add(currentPQP);
            if (currentPQP.getQuantity() > 0) {
                pqp = currentPQP;
                //currentPQP.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP.setSalesQuotation(current);

            currentPQP2.setProduct(getFacade().getSalesQuotationProduct("Classic Nutri Bar (Fruits)"));
            current.getPqp().add(currentPQP2);
            if (currentPQP2.getQuantity() > 0) {
                pqp = currentPQP2;
                //currentPQP2.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP2.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP2.setSalesQuotation(current);

            currentPQP3.setProduct(getFacade().getSalesQuotationProduct("Premium Power Bar (Chocolate Nuts)"));
            current.getPqp().add(currentPQP3);
            if (currentPQP3.getQuantity() > 0) {
                pqp = currentPQP3;
                //currentPQP3.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP3.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP3.setSalesQuotation(current);

            currentPQP4.setProduct(getFacade().getSalesQuotationProduct("Premium Power Bar (Redcurrant Fruits)"));
            current.getPqp().add(currentPQP4);
            if (currentPQP4.getQuantity() > 0) {
                pqp = currentPQP4;
                //currentPQP4.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP4.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP4.setSalesQuotation(current);

            current.setTotalPrice(currentPQP.getPrice() + currentPQP2.getPrice() + currentPQP3.getPrice() + currentPQP4.getPrice());

            //if sales executive create for sales lead, sales executive will quote price for sales lead
            if (checkSystemUser()) {
                current.setSystemUser(getCurrentUser()); //if requester is a customer, the system user creating it will usually be his executive, of course, other executives can quote price too
            } //if sales leads create by themselves, no sales excutive will be assigned to quote price for them yet.
            else if (checkSalesLead()) {
                current.setSalesLead(getLoginSalesLead());
            } else if (checkCustomer()) {
                current.setCustomer(getLoginCustomer());
                current.setSystemUser(current.getCustomer().getCustomerExecutive());
            }

            //Set Created By
            current.created(getLoginPerson());
            currentPQP.created(getLoginPerson());
            currentPQP2.created(getLoginPerson());
            currentPQP3.created(getLoginPerson());
            currentPQP4.created(getLoginPerson());

            //Set Validity
            Calendar cal = Calendar.getInstance();
            cal.setTime(getToday());
            cal.add(Calendar.DATE, 30);
            current.setValidity(cal.getTime());
            //Set Indicative Lead Time
            inventorySourcing(current);
            getFacade().create(current);

            if (current.getSalesLead() != null) {
                //current.getSalesLead().getSalesQuotations().add(current);
                salesLeadEntityController.setCurrent(current.getSalesLead());
                salesLeadEntityController.getCurrent().getSalesQuotations().add(current);
                salesLeadEntityController.update();
                //send internal message to sales manager if its sales lead. manager will assign someone to follow up.
                systemMessageController.getEjbFacade().createAndSendSystemMessage(getFacade().getManagerFromDept(Department.Sales.getName()),
                        current.getSalesLead().getFullname() + " has created Sales Quotation # " + current.getId() + ".",
                        "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
            } else if (current.getCustomer() != null) {
                //current.getCustomer().getSalesQuotations().add(current);
                getCustomerEntityController().setCurrent(current.getCustomer());
                getCustomerEntityController().getCurrent().getSalesQuotations().add(current);
                getCustomerEntityController().update();
                systemMessageController.getEjbFacade().createAndSendSystemMessage(current.getCustomer().getCustomerExecutive(),
                        current.getCustomer().getFullname() + " created Sales Quotation # " + current.getId() + ".",
                        "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
            }

            //begin timer, quotation will expire when validity period is due.
            if (current.getValidity() != null) {
                getFacade().scheduleTimer(current.getValidity(), current.getId());
            }

            //current = null;
            setCurrentPQP(null);
            setCurrentPQP2(null);
            setCurrentPQP3(null);
            setCurrentPQP4(null);
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesQuotationEntityCreated"));
            return viewAfterCreate();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    private SalesQuotationEntity inventorySourcing(SalesQuotationEntity salesQuotation) {
        boolean all = true;
        Date date = new Date();
        ArrayList<ProductQuantityPriceEntity> hold = new ArrayList<ProductQuantityPriceEntity>();
        ArrayList<ProductQuantityPriceEntity> pqp = new ArrayList<ProductQuantityPriceEntity>(salesQuotation.getPqp());
        for (int i = 0; i < pqp.size(); i++) {
            ProductQuantityPriceEntity p = new ProductQuantityPriceEntity();
            p.setQuantity(pqp.get(i).getQuantity());
            hold.add(p);
        }

        for (int j = 0; j < pqp.size(); j++) {
            if (pqp.get(j).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)")) {
                System.out.println("classicnuts");
                if (completedGoodsEntityController.getTotalClassicNutriBarNuts() < pqp.get(j).getQuantity()) {
                    all = false;
                    pqp.get(j).setQuantity(pqp.get(j).getQuantity() - completedGoodsEntityController.getTotalClassicNutriBarNuts());
                    System.out.println("required="+pqp.get(j).getQuantity());
                }
            } else if (pqp.get(j).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)")) {
                if (completedGoodsEntityController.getTotalClassicNutriBarFruits() < pqp.get(j).getQuantity()) {
                    all = false;
                    pqp.get(j).setQuantity(pqp.get(j).getQuantity() - completedGoodsEntityController.getTotalClassicNutriBarFruits());
                }
            } else if (pqp.get(j).getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)")) {
                if (completedGoodsEntityController.getTotalPremiumPowerBarNuts() < pqp.get(j).getQuantity()) {
                    all = false;
                    pqp.get(j).setQuantity(pqp.get(j).getQuantity() - completedGoodsEntityController.getTotalPremiumPowerBarNuts());
                }
            } else if (pqp.get(j).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)")) {
                if (completedGoodsEntityController.getTotalPremiumPowerBarFruits() < pqp.get(j).getQuantity()) {
                    all = false;
                    pqp.get(j).setQuantity(pqp.get(j).getQuantity() - completedGoodsEntityController.getTotalPremiumPowerBarFruits());
                }
            }
        }

        if (all) {
            salesQuotation.setIndicativeLeadTime(date);
        } else {
            salesQuotation.setIndicativeLeadTime(backOrderFacade.atpCheckForQuotation(salesQuotation));
        }

        for (int i = 0; i < hold.size(); i++) {
            pqp.get(i).setQuantity(hold.get(i).getQuantity());
        }
        return salesQuotation;
    }

    public String prepareSearch() {
        setSearchItems(getSearchItems());
        return "SearchList";
    }

    public DataModel getSearchItems() {
        if (getAttribute().equals("id")) {
            searchItems = ejbFacade.searchSalesQuotationById(getAttribute(), getInput());
        } else if (getAttribute().equals("Name")) {
            searchItems = ejbFacade.searchSalesQuotationByName(getAttribute(), getInput());
        }
        items = searchItems;
        return searchItems;
    }

    public String prepareEdit() {
        current = (SalesQuotationEntity) getItems().getRowData();
        editQuantity();
        return "Edit";
    }

    public String prepareEditQuantity() {
        editQuantity();
        return "Edit";
    }

    public String prepareQuote() {
        current = (SalesQuotationEntity) getItems().getRowData();
        return "/entities/salesQuotationEntity/Quote?faces-redirect=true";
    }

    public String prepareEditLeadTime() {
        current = (SalesQuotationEntity) getItems().getRowData();
        return "/entities/salesQuotationEntity/LeadTime?faces-redirect=true";
    }

    public String update() {
        try {
            Date today = new Date();
            //if user edit
            if (editQuantity) {
                userEdit();
                inventorySourcing(current);
            } else {

                ArrayList<ProductQuantityPriceEntity> pqp = new ArrayList<ProductQuantityPriceEntity>(current.getPqp());
                ArrayList<RoleEntity> role = new ArrayList<RoleEntity>(getCurrentUser().getRoles());
                boolean manager = false;
                for (int i = 0; i < role.size(); i++) {
                    if (role.get(i).getRoleName().equals("Sales Manager")) {
                        manager = true;
                        break;
                    }
                }
                for (int i = 0; i < pqp.size(); i++) {
                    if (pqp.get(i).getQuantity() != 0) {
                        if (manager) {
                            if ((getPrice(pqp.get(i), current).get(0) * 0.8) > pqp.get(i).getPricePerUnit()) {
                                throw new Exception("Your account only permits discounts up to 20%.");
                            }
                        } else if ((getPrice(pqp.get(i), current).get(0) * 0.9) > pqp.get(i).getPricePerUnit()) {
                            throw new Exception("Your account only permits discounts up to 10%.");
                        }
                    }
                }

                if (current.getValidity() != null && current.getValidity().after(today)) {
                    current.setValid(true);
                    getFacade().scheduleTimer(current.getValidity(), current.getId());
                }
            }

            current.setTotalPrice(calculateTotalPrice());
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesQuotationEntityUpdated"));
            return "/entities/salesQuotationEntity/View?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void editQuantity() {
        editQuantity = true;
    }

    private void userEdit() {

        //always set validity = false when user edit.
        current.setValid(false);
        //recalculate price
        ArrayList<ProductQuantityPriceEntity> pqp = new ArrayList<ProductQuantityPriceEntity>(current.getPqp());
        for (int i = 0; i < pqp.size(); i++) {
            pqp.get(i).setPrice(getPrice(pqp.get(i), current).get(1));
        }
        //send system mesage to remind executive to review
        if (current.getSalesLead() != null) {
            systemMessageController.getEjbFacade().createAndSendSystemMessage(
                    getFacade().getManagerFromDept(Department.Sales.getName()),
                    "Sales lead edited his sales quotation. Please review quotation again.",
                    "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
        }
        if (current.getCustomer() != null) {
            systemMessageController.getEjbFacade().createAndSendSystemMessage(
                    current.getCustomer().getCustomerExecutive(),
                    "Customer edited his sales quotation. Please review quotation again.",
                    "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
        }
        editQuantity = false;
    }

    private double calculateTotalPrice() {
        ArrayList<ProductQuantityPriceEntity> pqp = new ArrayList<ProductQuantityPriceEntity>(current.getPqp());
        double totalPrice = 0;
        for (int i = 0; i < pqp.size(); i++) {
            totalPrice = totalPrice + pqp.get(i).getPrice();
        }
        return totalPrice;
    }

    public String destroy() {
        current = (SalesQuotationEntity) getItems().getRowData();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();

        return "List";

    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesQuotationEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public String performConvert() {
        try {

            ProductQuantityPriceEntity pqp;
            convertingInquiry = getSalesInquiryEntityController().getSelected();

            if (currentPQP.getQuantity() > 0) {
                pqp = currentPQP;
                currentPQP.setPrice(getPrice(pqp, current).get(1));
            }
            current.getPqp().add(currentPQP);
            currentPQP.setSalesQuotation(current);

            if (currentPQP2.getQuantity() > 0) {
                pqp = currentPQP2;
                currentPQP2.setPrice(getPrice(pqp, current).get(1));
            }
            current.getPqp().add(currentPQP2);
            currentPQP2.setSalesQuotation(current);

            if (currentPQP3.getQuantity() > 0) {
                pqp = currentPQP3;
                currentPQP3.setPrice(getPrice(pqp, current).get(1));
            }
            current.getPqp().add(currentPQP3);
            currentPQP3.setSalesQuotation(current);

            if (currentPQP4.getQuantity() > 0) {
                pqp = currentPQP4;
                currentPQP4.setPrice(getPrice(pqp, current).get(1));
            }
            current.getPqp().add(currentPQP4);
            currentPQP4.setSalesQuotation(current);

            current.created(getLoginPerson());

            if (current.getSalesLead() != null) {
                salesLeadEntityController.setCurrent(current.getSalesLead());
                salesLeadEntityController.update();
            }
            if (current.getCustomer() != null) {
                getCustomerEntityController().setCurrent(current.getCustomer());
                getCustomerEntityController().update();
            }

            current.setTotalPrice(currentPQP.getPrice() + currentPQP2.getPrice() + currentPQP3.getPrice() + currentPQP4.getPrice());

            Calendar cal = Calendar.getInstance();
            cal.setTime(getToday());
            cal.add(Calendar.DATE, 30);
            current.setValidity(cal.getTime());

            convertingInquiry.setConverted(true);
            getSalesInquiryEntityController().getFacade().edit(convertingInquiry);
            inventorySourcing(current);
            getFacade().create(current);

            if (current.getSalesLead() != null) {
                systemMessageController.getEjbFacade().createAndSendSystemMessage(getFacade().getManagerFromDept(Department.Sales.getName()),
                        current.getSalesLead().getFullname() + " has created Sales Quotation # " + current.getId() + ".",
                        "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
            }
            if (current.getCustomer() != null) {
                systemMessageController.getEjbFacade().createAndSendSystemMessage(current.getCustomer().getCustomerExecutive(),
                        current.getCustomer().getFullname() + " created Sales Quotation # " + current.getId() + ".",
                        "/entities/salesQuotationEntity/List.xhtml", systemMessageController);
            }

            currentPQP = null;
            currentPQP2 = null;
            currentPQP3 = null;
            currentPQP4 = null;

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesInquiryEntityConverted"));
            return viewAfterCreate();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public DataModel getItems() {
        if (items == null) {
            if (getLoginPerson() instanceof SystemUserEntity) {
                items = getFacade().getAllSalesQuotation();
            } else if (getLoginPerson() instanceof SalesLeadEntity) {
                items = getFacade().getAllSalesQuotationForSalesLead(getLoginPerson().getId());
            } else if (getLoginPerson() instanceof CustomerEntity) {
                items = getFacade().getAllSalesQuotationForCustomer(getLoginPerson().getId());
            }
        }
        return items;
    }

    public void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public void setSearchItems(DataModel searchItems) {
        this.searchItems = searchItems;
    }

    public SalesInquiryEntityController getSalesInquiryEntityController() {
        return salesInquiryEntityController;
    }

    public void setSalesInquiryEntityController(SalesInquiryEntityController salesInquiryEntityController) {
        this.salesInquiryEntityController = salesInquiryEntityController;
        this.salesInquiryEntityController.setSalesQuotationEntityController(this);
    }

    public DataModel getUnquoted() {
        return unquoted;
    }

    public void setUnquoted(DataModel unquoted) {
        this.unquoted = unquoted;
    }

    public CustomerEntityController getCustomerEntityController() {
        return customerEntityController;
    }

    public void setCustomerEntityController(CustomerEntityController customerEntityController) {
        this.customerEntityController = customerEntityController;
    }

    public SalesLeadEntity getSelectedSalesLead() {
        return selectedSalesLead;
    }

    public void setSelectedSalesLead(SalesLeadEntity selectedSalesLead) {
        this.selectedSalesLead = selectedSalesLead;
    }

    public CustomerEntity getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(CustomerEntity selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    public PurchaseOrderEntityController getPurchaseOrderEntityController() {
        return purchaseOrderEntityController;
    }

    public void setPurchaseOrderEntityController(PurchaseOrderEntityController purchaseOrderEntityController) {
        this.purchaseOrderEntityController = purchaseOrderEntityController;
        this.purchaseOrderEntityController.setSalesQuotationEntityController(this);
    }

    public SystemMessageController getSystemMessageController() {
        return systemMessageController;
    }

    public void setSystemMessageController(SystemMessageController systemMessageController) {
        this.systemMessageController = systemMessageController;
    }

    public void setCurrentPQP(ProductQuantityPriceEntity currentPQP) {
        this.currentPQP = currentPQP;
    }

    public void setCurrentPQP2(ProductQuantityPriceEntity currentPQP2) {
        this.currentPQP2 = currentPQP2;
    }

    public void setCurrentPQP3(ProductQuantityPriceEntity currentPQP3) {
        this.currentPQP3 = currentPQP3;
    }

    public void setCurrentPQP4(ProductQuantityPriceEntity currentPQP4) {
        this.currentPQP4 = currentPQP4;
    }

    public SalesQuotationEntity getViewCurrent() {
        return viewCurrent;
    }

    public void setViewCurrent(SalesQuotationEntity viewCurrent) {
        this.viewCurrent = viewCurrent;
    }

    public String getJustification() {
        return justification;
    }

    public void setJustification(String justification) {
        this.justification = justification;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public CompletedGoodsEntityController getCompletedGoodsEntityController() {
        return completedGoodsEntityController;
    }

    public void setCompletedGoodsEntityController(CompletedGoodsEntityController completedGoodsEntityController) {
        this.completedGoodsEntityController = completedGoodsEntityController;
    }

    @FacesConverter(forClass = SalesQuotationEntity.class)
    public static class SalesQuotationEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SalesQuotationEntityController controller = (SalesQuotationEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "salesQuotationEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof SalesQuotationEntity) {
                SalesQuotationEntity o = (SalesQuotationEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SalesQuotationEntityController.class.getName());
            }
        }
    }

    public void setQuote(ActionEvent event) throws Exception {
        current.setSystemUser(getCurrentUser());
    }

    public void saveAndPost(ActionEvent event) throws Exception {
        current.setSystemUser(getCurrentUser());
        //send email to customer
        if (current.getSalesLead() != null) {
            Mailer.doSend("staff.merlion@gmail.com",
                    current.getSalesLead().getContact().getEmail(),
                    "", "Sales Quotation #" + current.getId() + "Reviewed", "Dear " + current.getSalesLead().getTitle() + " " + current.getSalesLead().getFullname() + ", your sales quotation has been reviewed.",
                    null, null);
        } else {
            Mailer.doSend("staff.merlion@gmail.com",
                    current.getCustomer().getContact().getEmail(),
                    "", "Sales Quotation #" + current.getId() + "Reviewed", "Dear " + current.getCustomer().getTitle() + " " + current.getCustomer().getFullname() + ", your sales quotation has been reviewed.",
                    null, null);
        }
    }

    public String getUnquotedItems() {
        unquoted = getFacade().getUnquoted();
        items = unquoted;
        return "Notquoted";
    }

    public Date getToday() {
        Date today = new Date();
        return today;
    }

    public boolean displayCustomerTab() {
        if (checkSystemUser() && getSelected().getSalesLead() == null) {
            return true;
        } else {
            return false;
        }
    }

    public boolean displaySalesLeadTab() {
        if (checkSystemUser() && getSelected().getCustomer() == null) {
            return true;
        } else {
            return false;
        }
    }

    public String salesLeadSelect(SelectEvent event) {
        current.setSalesLead(getSelectedSalesLead());
        System.out.println(current.getSalesLead().getId());
        return "Create?faces-redirect=true";
    }

    public String customerSelect(SelectEvent event) {
        current.setCustomer(getSelectedCustomer());
        return "Create?faces-redirect=true";
    }

    public String reset() {
        current.setSalesLead(null);
        current.setCustomer(null);
        setCurrentPQP(null);
        setCurrentPQP2(null);
        setCurrentPQP3(null);
        setCurrentPQP4(null);
        return "Create?faces-redirect=true";
    }

    public String prepareCreatePO() {
        System.out.println("in here");
        try {
            purchaseOrderEntityController.setSelected(null);
            purchaseOrderEntityController.getSelected().setSalesQuotation(current);
            ArrayList<ProductQuantityPriceEntity> pqplist = new ArrayList<ProductQuantityPriceEntity>(current.getPqp());
            for (int i = 0; i < pqplist.size(); i++) {
                if (pqplist.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)")) {
                    purchaseOrderEntityController.setCurrentPQP(pqplist.get(i));
                } else if (pqplist.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)")) {
                    purchaseOrderEntityController.setCurrentPQP2(pqplist.get(i));
                } else if (pqplist.get(i).getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)")) {
                    purchaseOrderEntityController.setCurrentPQP3(pqplist.get(i));
                } else if (pqplist.get(i).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)")) {
                    purchaseOrderEntityController.setCurrentPQP4(pqplist.get(i));
                }
            }
            if (current.getSalesLead() != null && current.getCustomer() == null) {
                purchaseOrderEntityController.getSelected().setSalesLead(current.getSalesLead());
            }
            if (current.getCustomer() != null) {
                purchaseOrderEntityController.getSelected().setCustomer(current.getCustomer());
            }
            purchaseOrderEntityController.resetContactAndAddresses();
            return "/entities/purchaseOrderEntity/Create?faces-redirect=true";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/entities/purchaseOrderEntity/Create.xhtml";
    }

    public ArrayList<Double> getPrice(ProductQuantityPriceEntity pqp, SalesQuotationEntity quotation) {
        System.out.println("gettingprice");
        PriceListEntity priceList;

        if (quotation.getSalesLead() != null) {
            if (quotation.getSalesLead().getCustomerType().equals(CustomerType.Wholesales)) {
                priceList = getTypePriceList(CustomerType.Wholesales, pqp);
            } else {
                priceList = getTypePriceList(CustomerType.Directsales, pqp);
            }
        } else {
            if (quotation.getCustomer().getCustomerType().equals(CustomerType.Wholesales)) {
                priceList = getTypePriceList(CustomerType.Wholesales, pqp);
            } else {
                priceList = getTypePriceList(CustomerType.Directsales, pqp);
            }
        }
        return calculatePrice(pqp, priceList);
    }

    public PriceListEntity getTypePriceList(CustomerType type, ProductQuantityPriceEntity pqp) {
        System.out.println("gettingtype");
        PriceListEntity typePriceList = new PriceListEntity();
        ArrayList<PriceListEntity> priceList = getFacade().getPriceList();

        for (int i = 0; i < priceList.size(); i++) {
            if (priceList.get(i).getProduct().getId() == pqp.getProduct().getId() && priceList.get(i).getType().equals(type) && pqp.getQuantity() >= priceList.get(i).getTieredQuantity()) {
                typePriceList = priceList.get(i);
            }
        }
        return typePriceList;
    }

    public ArrayList<Double> calculatePrice(ProductQuantityPriceEntity pqp, PriceListEntity priceList) {
        System.out.println("calculating price");
        ArrayList price = new ArrayList<Double>();
        price.add(priceList.getPrice());
        price.add(pqp.getQuantity() * priceList.getPrice());
        return price;
    }

    public void actionsFromViewCreate(ActionEvent event) {
        current = viewCurrent;
        recreateModel();
    }

    public void recommendDiscount() {
        systemMessageController.getEjbFacade().createAndSendSystemMessage(getFacade().getManagerFromDept(Department.Sales.getName()),
                "Discount Recommendation for Sales Quotation # " + current.getId() + " by " + getCurrentUser().getName() + ". Justification: " + justification,
                "/index", systemMessageController);
        justification = "";
    }

    public void saveNote() {
        Date now = getToday();
        SimpleDateFormat sdfDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
        current.getServiceRequests().add(getCurrentUser().getName() + " (" + sdfDate.format(now) + "): " + note);
        //getFacade().edit(current);
        note = "";
        //return "/entities/salesQuotationEntity/Quote?faces-redirect=true";
    }

    public void updatePricePerUnitTotalPrice(SalesQuotationEntity salesQuotation, ProductQuantityPriceEntity pqp, double pricePerUnit) {
        double totalPrice = 0;
        pqp.setPrice(pricePerUnit * pqp.getQuantity());
        ArrayList<ProductQuantityPriceEntity> allPqp = new ArrayList<ProductQuantityPriceEntity>(salesQuotation.getPqp());
        for (int i = 0; i < allPqp.size(); i++) {
            totalPrice = totalPrice + allPqp.get(i).getPrice();
        }
        salesQuotation.setTotalPrice(totalPrice);
    }
}
